package com.jike.noobmoney.mvp.view.activity;

import android.Manifest;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.image.imagepicker.ImagePicker;
import com.image.imagepicker.bean.ImageItem;
import com.image.imagepicker.ui.ImageGridActivity;
import com.jike.noobmoney.R;
import com.jike.noobmoney.contants.ConstantValue;
import com.jike.noobmoney.entity.BaseEntity;
import com.jike.noobmoney.entity.UserInfoEntity;
import com.jike.noobmoney.helper.ImageLoader;
import com.jike.noobmoney.mvp.presenter.AppPresenter;
import com.jike.noobmoney.mvp.presenter.UserPresenter;
import com.jike.noobmoney.mvp.view.widget.BottomDialog;
import com.jike.noobmoney.net.IView;
import com.jike.noobmoney.net.RetrofitHelper;
import com.jike.noobmoney.rxbus.RxBus;
import com.jike.noobmoney.rxbus.RxBusRoute;
import com.jike.noobmoney.rxbus.RxEvent;
import com.jike.noobmoney.util.SPUtils;
import com.jike.noobmoney.util.ToastUtils;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Create by xuke on 2018/11/10
 * 我的资料 (未完成)
 */
public class MyInfoActivity extends BaseActivity implements IView {

    private static final int REQUEST_CODE_SELECT = 111;

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_avatar)
    ImageView ivAvatar;
    @BindView(R.id.rl_avatar)
    RelativeLayout rlAvatar;
    @BindView(R.id.tv_nick)
    TextView tvNick;
    @BindView(R.id.rl_nick)
    RelativeLayout rlNick;
    @BindView(R.id.tv_gender)
    TextView tvGender;
    @BindView(R.id.rl_gender)
    RelativeLayout rlGender;
    @BindView(R.id.tv_birthday)
    TextView tvBirthday;
    @BindView(R.id.rl_birthday)
    RelativeLayout rlBirthday;
    @BindView(R.id.tv_mobile)
    TextView tvMobile;
    @BindView(R.id.rl_mobile)
    RelativeLayout rlMobile;
    @BindView(R.id.tv_user_info)
    TextView tvUserInfo;
    private String userid;
    private Call<UserInfoEntity> userInfoCall;

    private AppPresenter appPresenter;
    private UserPresenter userPresenter;
    private String url;

    @Override
    protected int layoutResID() {
        return R.layout.activity_my_info;
    }

    @Override
    protected void initData() {
        tvTitle.setText("我的资料");
        userid = SPUtils.getInstance().getString(ConstantValue.SpType.userid);

        appPresenter = new AppPresenter(this);
        userPresenter = new UserPresenter(this);
        getData();
    }

    /**
     * 获取个人信息
     */
    private void getData() {
        userInfoCall = RetrofitHelper.getInstance().getUserInfo(userid);
        userInfoCall.enqueue(new Callback<UserInfoEntity>() {
            @Override
            public void onResponse(Call<UserInfoEntity> call, Response<UserInfoEntity> response) {
                if (response != null) {
                    UserInfoEntity body = response.body();
                    if (body != null && "100".equals(body.getCode())) {
                        UserInfoEntity.UserBean user = body.getUser();
                        if (user != null) {
                            initView(user);
                        }
                    }
                }
            }

            @Override
            public void onFailure(Call<UserInfoEntity> call, Throwable t) {
                ToastUtils.showShortToastSafe(t.getMessage());
            }
        });
    }

    /**
     * 设置用户信息
     */
    private void initView(UserInfoEntity.UserBean user) {
        //头像
        if (!TextUtils.isEmpty(user.getAvatar()) && user.getAvatar() != null) {
            String url = ConstantValue.IMG_BASEURL + user.getAvatar();
            ImageLoader.displayImageDefaultHead(this, url, ivAvatar);

        } else {
            ImageLoader.displayImageDefaultHead(context, R.drawable.ic_user_default, ivAvatar);
        }

        //昵称
        tvNick.setText(TextUtils.isEmpty(user.getNick()) ? "小白赚钱" : user.getNick());
        //性别
        tvGender.setText(TextUtils.isEmpty(user.getGender()) ? "未知" : user.getGender());
        //出生日期
        tvBirthday.setText(TextUtils.isEmpty(user.getBirthday()) ? "2018-11-12" : user.getBirthday());
        //手机号
        tvMobile.setText(user.getMobile());

    }


    @OnClick({R.id.iv_back, R.id.iv_avatar, R.id.rl_avatar, R.id.tv_nick, R.id.rl_nick, R.id.tv_gender, R.id.rl_gender, R.id.tv_birthday, R.id.rl_birthday, R.id.tv_mobile, R.id.rl_mobile, R.id.tv_user_info})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.iv_avatar:
            case R.id.rl_avatar:
                //头像
                showOptions();
                break;
            case R.id.tv_nick:
            case R.id.rl_nick:
                //昵称
                Intent intent = new Intent(this, EditNameActivity.class);
                intent.putExtra("name", tvNick.getText().toString().trim());
                startActivityForResult(intent, 100);
                break;
            case R.id.tv_gender:
            case R.id.rl_gender:
                //性别
                selectGender();
                break;
            case R.id.tv_birthday:
            case R.id.rl_birthday:
                //生日
                selectBirthday();
                break;
            case R.id.tv_mobile:
            case R.id.rl_mobile:
                //修改手机号
                break;
            case R.id.tv_user_info:
                //确认修改
                confirm();
                break;
        }
    }

    /**
     * 选择性别
     */
    private void selectGender() {

        List<String> options1Items = new ArrayList<>();
        options1Items.add("男");
        options1Items.add("女");

        //条件选择器
        OptionsPickerView pvOptions = new OptionsPickerBuilder(this, (options1, option2, options3, v) -> {
            tvGender.setText(options1Items.get(options1));
        })
                .setSubmitColor(getResources().getColor(R.color.c_main))     //确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.c_cccccc))   //取消按钮文字颜色
                .build();
        pvOptions.setPicker(options1Items);
        pvOptions.show();

    }

    /**
     * 选择生日
     */
    private void selectBirthday() {
        TimePickerView pvTime = new TimePickerBuilder(this, (date, v) -> {
            String s = dateToString(date, "yyyy-MM-dd");
            tvBirthday.setText(s);
        })
                .setSubmitColor(getResources().getColor(R.color.c_main))     //确定按钮文字颜色
                .setCancelColor(getResources().getColor(R.color.c_cccccc))   //取消按钮文字颜色
                .build();
        pvTime.show();
    }

    public static String dateToString(Date data, String formatType) {
        return new SimpleDateFormat(formatType).format(data);
    }


    /**
     * 弹出底部框
     */
    private void showOptions() {
        setImagePicker();
        BottomDialog bottomDialog = BottomDialog.getInstance();
        bottomDialog.show(getSupportFragmentManager(), "takephoto");
        bottomDialog.setClickCallback(new BottomDialog.OnClickCallback() {
            @Override
            public void item1Click() {
                new RxPermissions(MyInfoActivity.this)
                        .request(Manifest.permission.CAMERA)
                        .subscribe(granted -> {
                            if (granted) {
                                takePhoto();
                            } else {
                                ToastUtils.showShortToastSafe("您拒绝了调用相机拍照");
                            }
                        });
                bottomDialog.dismiss();
            }

            @Override
            public void item2Click() {
                pickImage();
                bottomDialog.dismiss();
            }

            @Override
            public void cancel() {
                bottomDialog.dismiss();
            }
        });
    }

    private void setImagePicker() {
        ImagePicker.getInstance().setSelectLimit(1);
        ImagePicker.getInstance().setCrop(true);
        ImagePicker.getInstance().setMultiMode(false);
        ImagePicker.getInstance().setSaveRectangle(true);
        ImagePicker.getInstance().setFocusHeight(800);
        ImagePicker.getInstance().setFocusWidth(800);
        ImagePicker.getInstance().setOutPutY(800);
        ImagePicker.getInstance().setOutPutX(800);
    }

    /**
     * 拍照
     */
    private void takePhoto() {
        Intent intent = new Intent(context, ImageGridActivity.class);
        intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true);
        startActivityForResult(intent, REQUEST_CODE_SELECT);

    }

    /**
     * 相册
     */
    private void pickImage() {
        Intent intent1 = new Intent(context, ImageGridActivity.class);
        startActivityForResult(intent1, REQUEST_CODE_SELECT);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("xuke", "requestCode=" + requestCode);

        switch (requestCode) {
            case REQUEST_CODE_SELECT: {
                try {
                    ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                    String sourcePath = images.get(0).getPath();

                    showProgress();
                    appPresenter.upload(new File(sourcePath), ConstantValue.RequestKey.uploadfile);

                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
        }

        if (requestCode == 100 && resultCode == 200) {
            String s = data.getStringExtra("newName");
            tvNick.setText(s);
        }
    }


    /**
     * 确认提交
     */
    private void confirm() {
        String nick = tvNick.getText().toString().trim();
        String gender = tvGender.getText().toString().trim();
        String birthday = tvBirthday.getText().toString().trim();

        showProgress();
        //userPresenter.editUserInfo1(userid, nick, gender, birthday, "upload_userinfo");
    }


    @Override
    public void onSuccess(String code, String msg, Object data, String actionType) {
        dismissProgress();
        if (ConstantValue.RequestKey.uploadfile.equals(actionType)) {
            url = (String) data;

            showProgress();
            userPresenter.editUserInfo2(userid, url, "upload_avatar");
        }

        if ("upload_avatar".equals(actionType)) {
            ToastUtils.showShortToastSafe(msg);
            //头像上传成功
            String url2 = ConstantValue.IMG_BASEURL + url;
            ImageLoader.displayImageDefaultHead(this, url2, ivAvatar);
            SPUtils.getInstance().put(ConstantValue.SpType.newavatar, url);

            RxBus.getInstance().post(new RxEvent(RxBusRoute.REFRESH_USER_INFO));
        }

        if ("upload_userinfo".equals(actionType)) {
            ToastUtils.showShortToastSafe(msg);

            SPUtils.getInstance().put(ConstantValue.SpType.nick, tvNick.getText().toString().trim());
            RxBus.getInstance().post(new RxEvent(RxBusRoute.REFRESH_USER_INFO));
        }


    }

    @Override
    public void onFailed(String code, String msg) {
        ToastUtils.showShortToastSafe(msg);
        dismissProgress();
    }
}
